iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 18
0
自我挑戰組

Tensorflow.js初學筆記系列 第 18

Day17 TensorFlow.js 物件辨識

  • 分享至 

  • xImage
  •  

今天一樣是用Google提供的model
不多說,直接先上程式碼

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>cocossd test</title>
    <!-- TensorFlow.js Core -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js">
    </script>
    <!-- TensorFlow.js mobilenet model -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd">
    </script>
    <style>
        img {
            width: 400px;
            height: 400px;
            display: none;
        }

    </style>
</head>

<body>  
    <h1>測試物件辨識</h1>
    <img id="detect_img" crossorigin src="https://i.imgur.com/fcegPaI.jpg" />
    <canvas id="detect_result"></canvas>
    <script>
        const color=["green","yellow","red"]
        async function app() {
            const model = await cocoSsd.load();
            const img = document.getElementById('detect_img');
            const result = await model.detect(img);
            const canvas = document.getElementById('detect_result');
            canvas.width=img.naturalWidth;
            canvas.height=img.naturalHeight;
            const context = canvas.getContext('2d');
            context.drawImage(img, 0, 0);
            context.font = '40px Arial';
            
            for (let i = 0; i < result.length; i++) {
                context.beginPath();
                //three dots mean spread over object get all its properties
                context.rect(...result[i].bbox);
                context.lineWidth = 5;
                context.strokeStyle = color[i%3];
                context.fillStyle = color[i%3];
                context.stroke();
                context.fillText(
                    result[i].score.toFixed(3) + ' ' + result[i].class, 
                    result[i].bbox[0],
                    result[i].bbox[1] - 5);
            }
        }
        app();

    </script>
</body>

</html>

結果

不知道為什麼沒有測到貓


上一篇
Day16 TensorFlow.js 即時影像辨識分類
下一篇
Day18 TensorFlow.js 即時物件辨識
系列文
Tensorflow.js初學筆記27
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言